package com.qys.livesMall.navy.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.navy.model.dto.EditNavyShopBalance;
import com.qys.livesMall.navy.model.dto.EditNavyShopName;
import com.qys.livesMall.navy.model.dto.NavyEditShop;
import com.qys.livesMall.navy.model.dto.NavyShopAddGoods;
import com.qys.livesMall.product.entity.H2ProductGoodsinfo;
import com.qys.livesMall.product.entity.H2ProductSku;
import com.qys.livesMall.product.service.H2ProductGoodsinfoService;
import com.qys.livesMall.product.service.H2ProductSkuService;
import com.qys.livesMall.shop.constants.ShopConstant;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.enums.ShopBalanceTradeTypeEnum;
import com.qys.livesMall.shop.enums.ShopBusinessTypeEnum;
import com.qys.livesMall.shop.enums.ShopMessageEnum;
import com.qys.livesMall.shop.modal.dto.PurchaseSku;
import com.qys.livesMall.shop.modal.dto.shop.AppPurchase;
import com.qys.livesMall.shop.modal.dto.shop.ShopSearch;
import com.qys.livesMall.shop.modal.dto.shop.balance.ShopBalanceHandle;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.service.H2ShopBalanceService;
import com.qys.livesMall.shop.service.H2ShopBaseService;
import com.qys.livesMall.shop.service.ShopPurchaseInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @menu NavyShopServer
 * @date 2023/07/05 10:36
 */
@Slf4j
@Service
public class NavyShopServer {

    @Autowired
    private MessageServer messageServer;

    @Autowired
    private H2ShopBalanceService shopBalanceService;

    @Autowired
    private H2ShopBaseService shopBaseService;

    @Resource
    private ShopPurchaseInfoService purchaseInfoService;

    @Resource
    private H2ProductGoodsinfoService productInfoService;

    @Resource
    private H2ProductSkuService productSkuService;

    @Resource
    private H2ShopBaseDao h2ShopBaseDao;

    public R editBalance(EditNavyShopBalance shopBalance){
        if (CollectionUtils.isEmpty(shopBalance.getShopIds())||shopBalance.getAmount()==null){
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        shopBalance.getShopIds().stream().forEach(shopId ->{
            H2ShopBase shopBase = shopBaseService.queryById(shopId);
            if(null == shopBase){
                throw new QysException(ShopMessageEnum.SHOP_NOT_EXIST);
            }

            ShopBalanceHandle balanceHandle = new ShopBalanceHandle();
            balanceHandle.setUserId(shopBase.getUserId());
            balanceHandle.setShopId(shopId);
            balanceHandle.setAmountIncurred(shopBalance.getAmount());
            balanceHandle.setPayMethod(ShopConstant.PayMethod.BALANCE);

            ShopBalanceHandle handle = new ShopBalanceHandle();
            if(ShopBusinessTypeEnum.DEDUCT.getType().equals(shopBalance.getCategory())){
                //扣款
                balanceHandle.setBusinessNo(ShopBusinessTypeEnum.DEDUCT.getPrefix());
                balanceHandle.setTradeTypeEnum(ShopBalanceTradeTypeEnum.OUT);
                balanceHandle.setCategory(ShopBusinessTypeEnum.DEDUCT.getType());
                handle = shopBalanceService.directOut(balanceHandle);
            }else if(ShopBusinessTypeEnum.GIFT.getType().equals(shopBalance.getCategory())){
                //赠送
                balanceHandle.setBusinessNo(ShopBusinessTypeEnum.GIFT.getPrefix());
                balanceHandle.setTradeTypeEnum(ShopBalanceTradeTypeEnum.IN);
                balanceHandle.setCategory(ShopBusinessTypeEnum.GIFT.getType());
                handle = shopBalanceService.directIn(balanceHandle);
            }

            if(!handle.getSuccess()){
                log.error("店铺："+shopId+":水军店铺余额修改失败："+messageServer.getMsg(handle.getMessage()));
            }
        });
        return R.ok();
    }

    public R editName(EditNavyShopName navyShopName){
        if (CollectionUtils.isEmpty(navyShopName.getShopIds())|| StringUtils.isEmpty(navyShopName.getNames())){
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }

        List<String> names= Arrays.stream(navyShopName.getNames().split(",")).toList();
        int count=navyShopName.getShopIds().size()-names.size();
        if (count>0){
            navyShopName.setShopIds(navyShopName.getShopIds().subList(0,names.size()));
        }else if (count<0){
            names=names.subList(0,navyShopName.getShopIds().size());
        }

        List<H2ShopBase> shops=new ArrayList<>();
        for(int i=0;i<navyShopName.getShopIds().size();i++){
            H2ShopBase shop=new H2ShopBase();
            shop.setId(navyShopName.getShopIds().get(i));
            shop.setShopName(names.get(i));
            shop.setUpdateTime(LocalDateTime.now());
            shops.add(shop);
        }
        shopBaseService.upBatch(shops);
        return R.ok();
    }
    public R listNavyShop(ShopSearch shopSearch) {
//        水军店铺
        shopSearch.setType(2);
        return R.ok(shopBaseService.list(shopSearch));
    }

    public R addProduct(NavyShopAddGoods navyShopAddGoods) {

        if ((null == navyShopAddGoods.getGoodsNum() && StringUtils.isBlank(navyShopAddGoods.getGoodsId()))
                || null == navyShopAddGoods.getTotal()) {
            return R.fail(messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR));
        }
        Integer goodsNum = navyShopAddGoods.getGoodsNum();
  //      appPurchase.setTotalNum(navyShopAddGoods.getGoodsNum());
//        货到付款

        LambdaQueryWrapper<H2ProductGoodsinfo> productGoodsQuery = Wrappers.lambdaQuery(H2ProductGoodsinfo.class);
        if (StringUtils.isNotBlank(navyShopAddGoods.getGoodsId())) {
            productGoodsQuery.eq(H2ProductGoodsinfo::getId, navyShopAddGoods.getGoodsId());
        } else {
            productGoodsQuery.ge(H2ProductGoodsinfo::getNum, navyShopAddGoods.getGoodsNum())
                    .last("order by rand() limit " + navyShopAddGoods.getTotal());
        }
//        单个商品时校验库存
        List<H2ProductGoodsinfo> list = productInfoService.list(productGoodsQuery);
        if (CollectionUtils.isEmpty(list)){
            return R.fail(messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR));//未
            // 找到商品
        }
        List<H2ProductSku> allSkus=new ArrayList<>();
        list.stream().forEach(goods->{
            LambdaQueryWrapper<H2ProductSku> skuQuery=new LambdaQueryWrapper<>();
            skuQuery.eq(H2ProductSku::getSpuId,goods.getId());
            List<H2ProductSku> skuList=productSkuService.list(skuQuery);
            if (!CollectionUtils.isEmpty(skuList)){
                allSkus.addAll(skuList);

            }
        });
        AppPurchase appPurchase = new AppPurchase();

        appPurchase.setPayType("2");
        appPurchase.setShopId(navyShopAddGoods.getShopId());
        appPurchase.setNavyUser(true);
        List<PurchaseSku> skus=new ArrayList<>();
        allSkus.stream().forEach(sku->{
            PurchaseSku purchaseSku=new PurchaseSku();
            purchaseSku.setSkuId(sku.getId());
            purchaseSku.setNum(navyShopAddGoods.getGoodsNum());//每种sku数量
        });

//        设置采购参数
        return purchaseInfoService.addList(appPurchase);
    }

    public R edit(NavyEditShop navyEditShop) {
        H2ShopBase shop = h2ShopBaseDao.getById(navyEditShop.getId());
        if (shop == null) {
            //店铺不存在
            return messageServer.failMsg(ShopMessageEnum.SHOP_NOT_EXIST);
        }
        BeanUtils.copyProperties(navyEditShop, shop);
        h2ShopBaseDao.updateById(shop);
        return R.ok();
    }

    public R getNavyShopDetail(Long shopId) {
        return R.ok(h2ShopBaseDao.getById(shopId));
    }
}

